package com.fly.controller;

import com.fly.bean.UserLog;
import com.fly.bean.Users;
import com.fly.service.UserService;
import com.fly.util.JWTUtil;
import com.fly.util.Md5Util;
import com.fly.util.Msg;
import com.fly.vo.ChangePwd_ZL;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    /**
     * 用户登录
     *  需判断该用户的用户状态和该用户所对应的角色状态是否为启用，如果有一个未启用则不能登录成功
     * @param userName
     * @param userPwd
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public Msg login(@RequestParam("userName") String userName, @RequestParam("userPwd") String userPwd) {

        //根据用户名查询用户Id
        Integer userId = userService.selectUserIdByUserName(userName);
        //根据用户Id查询角色Id
        Integer roleId = userService.selectRoleIdByUserId(userId);
        //根据用户Id查询userState
        Integer userState = userService.selectUserStateByUserId(userId);
        //根据角色Id查询roleState
        Integer roleState = userService.selectRoleStateByRoleId(roleId);
        //根据userState查询sysProValueName
        String userSysProValueName = userService.selectSysProValueNameByUserState(userState);
        //根据roleState查询sysProValueName
        String roleSysProValueName = userService.selectSysProValueNameByRoleState(roleState);

        if ("启用".equals(roleSysProValueName) && "正常".equals(userSysProValueName)){
            //密码加密
            String newPwd = Md5Util.setDBPwd(userPwd);
            Users user = userService.getUserByUserNameAndUserPwd(userName, newPwd);

            if (user != null) {
                //给用户jwt加密生成token
                String token = JWTUtil.sign(user, 10000L * 60L * 30L);
                //给密码加密
                user.setUserPwd("加密");

                //创建日志对象
                UserLog userLog = new UserLog();
                //操作对象
                userLog.setUser(user);

                //创建用户登录的时间
                Date date = new Date();
//            System.out.println(date);
                //操作信息
                userLog.setUserLogOperationInformation("用户" + user.getUserName() + "在" + date + "登录");
                //操作时间
                userLog.setUserLogOperationDate(date);
                //添加日志信息
                userService.addUserLog(userLog);
                //登录成功返回user和token以及状态等信息
                return Msg.success().add("user", user).add("token", token);
            } else {
                //登录失败返回状态码和信息
                return Msg.fail();
            }
        }else {
            return Msg.fail();
        }
    }

    /**
     * 显示用户信息
     *
     * @param userId
     * @return
     */
    @RequestMapping("/showUser")
    @ResponseBody
    public Msg showUser(@RequestParam("userId") Integer userId) {
        Users user = null;

        try {
            user = userService.getUserById(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (user != null) {
            //给用户jwt加密生成token
            String token = JWTUtil.sign(user, 1000L * 60L * 20L);

            user.setUserPwd("加密");
            //登录成功返回user和token以及状态等信息
            return Msg.success().add("user", user).add("token", token);
        } else {
            //登录失败返回状态码和信息
            return Msg.fail();
        }
    }

    /**
     * 修改用户信息
     *
     * @param userId
     * @param userName
     * @param sex
     * @param age
     * @param joinDate
     * @param leavingDate
     * @param phone
     * @param email
     * @return
     */
    @RequestMapping("/modifyUser")
    @ResponseBody
    public Msg modifyUser(Integer userId, String userName,String sex, Integer age, Date joinDate, Date leavingDate, String phone, String email) {
        Users user = new Users(userId, userName, sex, age, joinDate, leavingDate, phone, email);
        if (user != null) {
            userService.modifyUserById(user);

            //创建日志对象
            UserLog userLog = new UserLog();
            //操作对象
            userLog.setUser(user);

            //创建用户登录的时间
            Date date = new Date();
//            System.out.println(date);
            //操作信息
            userLog.setUserLogOperationInformation("用户" + user.getUserName() + "在" + date + "修改了一些信息");
            //操作时间
            userLog.setUserLogOperationDate(date);
            //添加日志信息
            userService.addUserLog(userLog);

            //修改成功返回成功信息
            return Msg.success();
        } else {
            //修改失败返回失败信息
            return Msg.fail();
        }
    }

    /**
     * 修改密码
     * @param changePwd
     * @param request
     * @return
     */
    @RequestMapping(value = "/modifyPassword")
    @ResponseBody
    public Msg modifyPassword(@RequestBody ChangePwd_ZL changePwd, HttpServletRequest request){
        //开始用户认证
        String token = request.getHeader("Authorization");
        //解密token
        Users user = JWTUtil.unsign(token, Users.class);
        //给原密码加密进行比较
        String md5OldPwd = Md5Util.setDBPwd(changePwd.getOldPwd());
        //查询原密码是否正确
        System.out.println(user.getUserId());
        Integer srcPwdResult = userService.selectSrcUserPwdByUserId(user.getUserId(),md5OldPwd);
        if (srcPwdResult > 0){
            Users user1 = new Users();
            user1.setUserId(user.getUserId());

            //MD5加密
            String newPwd = Md5Util.setDBPwd(changePwd.getNewPwd());
            user1.setUserPwd(newPwd);
            Integer newPwdResult = userService.modifyPassword(user1);

            if (newPwdResult > 0){
                return Msg.success();
            }else {
                return Msg.fail();
            }
        }else{
            return Msg.fail();
        }
    }

    /**
     * 退出登录，通过userId插入日志信息
     * 前端需要请求传入userId，然后删除token信息
     * @param userId
     * @return
     */
    @RequestMapping("/loginOut")
    @ResponseBody
    public Msg loginOut(Integer userId){
        //根据userId查询用户信息
        Users user = userService.getUserById(userId);
        //创建日志对象
        UserLog userLog = new UserLog();
        //操作对象
        userLog.setUser(user);

        //创建用户登录的时间
        Date date = new Date();
        //操作信息
        userLog.setUserLogOperationInformation("用户" + user.getUserName() + "在" + date + "退出登录");
        //操作时间
        userLog.setUserLogOperationDate(date);
        //添加日志信息
        userService.addUserLog(userLog);

        if (userLog != null){
            return Msg.success();
        }else{
            return Msg.fail();
        }
    }

    @RequestMapping("/encryption")
    @ResponseBody
    public Msg encryption(){
        //查询得到所有的用户信息
        List<Users> userPasswords = userService.selectAllPassword();

        //标识
        boolean flag = false;

        for (Users user : userPasswords){
            //进行MD5加密
            String newPwd = Md5Util.setDBPwd(user.getUserPwd());
            user.setUserPwd(newPwd);
            //修改密码
            Integer result = userService.modifyPassword(user);
            if (result > 0){
                flag = true;
            }else {
                flag = false;
            }
        }
        if (flag){
            return Msg.success();
        }else {
            return Msg.fail();
        }
    }
}